package org.lib.mongodbhello.try2;

import java.util.Date;
import java.util.Objects;

import org.lib.mongodbhello.try2.dao.User2Dao;
import org.lib.mongodbhello.try2.dto.AddUser2DTO;
import org.lib.mongodbhello.try2.dto.UpdateUser2DTO;
import org.lib.mongodbhello.try2.entity.User2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

/**
 * 试验2接口
 * @author ben
 * @date 2021-08-25 16:17:32 CST
 */
@RestController
@RequestMapping(value="/try2")
@Slf4j
public class Try2Controller {

	@Autowired
	private User2Dao user2Dao;
	
	/**
	 * 添加
	 * @author ben
	 * @date 2021-08-25 16:21:10 CST
	 * @param dto
	 * @return
	 */
	@PostMapping(value="/add")
	public User2 add(@RequestBody AddUser2DTO dto) {
		User2 u = new User2(dto.getName(), dto.getAge());
		user2Dao.save(u);
		log.info("添加User2：id={}", u.getId());
		return u;
	}
	
	/**
	 * 查找
	 * @author ben
	 * @date 2021-08-25 16:24:09 CST
	 * @param id
	 * @return
	 */
	@GetMapping(value="/get")
	public User2 get(@RequestParam String id) {
		if (Objects.isNull(id)) {
			return null;
		}
		
		return user2Dao.findById(id).orElse(null);
	}
	
	/**
	 * 更新
	 * @author ben
	 * @date 2021-08-25 16:26:04 CST
	 * @param dto
	 * @return
	 */
	@PostMapping(value="/update")
	public User2 update(@RequestBody UpdateUser2DTO dto) {
		String id = dto.getId();
		if (Objects.isNull(id)) {
			return null;
		}
		
		User2 oldUser2 = user2Dao.findById(id).orElse(null);
		if (Objects.isNull(oldUser2)) {
			return null;
		}
		
		StringBuffer sb = new StringBuffer();
		boolean needUpdate = false;
		if (Objects.nonNull(dto.getName())) {
			oldUser2.setName(dto.getName());
			needUpdate = true;
			sb.append("更新name;");
		}
		if (Objects.nonNull(dto.getAge())) {
			oldUser2.setAge(dto.getAge());
			needUpdate = true;
			sb.append("更新age;");
		}
		if (needUpdate) {
			oldUser2.setUpdateTime(new Date());
			User2 nu = user2Dao.save(oldUser2);
			log.info("更新User2：id={}", id);
			return nu;
		}
		
		return null;
	}
	
	/**
	 * 删除：成功删除（或不存在、或参数错误）返回false
	 * @author ben
	 * @date 2021-08-25 16:41:59 CST
	 * @param id
	 * @return
	 */
	@DeleteMapping(value="/del")
	public Boolean del(@RequestParam String id) {
		if (!StringUtils.hasText(id)) {
			return false;
		}
		
		// 无返回值
		user2Dao.deleteById(id);
		
		return user2Dao.existsById(id);
	}
	
}
